package tgc.edu.ljc.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import tgc.edu.ljc.custom.CommonService;
import tgc.edu.ljc.entity.TbMenu;
import tgc.edu.ljc.repository.TbMenuRepository;
import tgc.edu.ljc.security.UserUtils;
@Service
public class TbMenuService extends CommonService<TbMenu, Integer>{
	@Autowired
	private TbMenuRepository tbMenuDAO;

	@Autowired
	private UserUtils userUtils;
	

	private List<TbMenu> auditMenu(List<TbMenu> menus) {
		List<TbMenu> list=new ArrayList<>();
		for (TbMenu menu : menus) {
			String code = menu.getRole().getCode();
			if(userUtils.hasRole(code)) {
				list.add(menu);
				if(menu.getChildren()!=null&&!menu.getChildren().isEmpty()) {
					menu.setChildren(auditMenu(menu.getChildren()));
				}
			}
		}
		return list;
	}

	/***
	 * 取出用户有权限的菜单项
	 *
	 * @return 用户要显示的菜单项
	 */

	public List<TbMenu> findAuditMenu() {
		List<TbMenu> menus;
		if(userUtils.hasRole("ROLE_DIY")) {
			menus=tbMenuDAO.findByParentIsNullOrderByIdx1();
		}else {
			menus=auditMenu(tbMenuDAO.findByParentIsNullOrderByIdx1());
		}
		return menus;
	}
}
